package com.tssf.car_manage.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径和方法
        String requestURI = request.getRequestURI();
        String method = request.getMethod();

        // 放行公开路径（新增逻辑）
        if (isPublicPath(requestURI)) {
            return true;
        }

        // 检查Session（保持您原有逻辑，但优化session获取方式）
        HttpSession session = request.getSession(false); // 改为不自动创建session

        // 新增session失效处理逻辑
        if (session == null || session.getAttribute("loginUser") == null) {
            handleUnauthorized(request, response, method);
            return false;
        }

        // 保持您原有的权限检查逻辑
        return checkRolePermission(requestURI, session.getAttribute("loginRole"));
    }

    // ============= 以下是新增的辅助方法 =============

    /**
     * 检查是否为公开路径
     */
    private boolean isPublicPath(String uri) {
        String[] publicPaths = {"/", "/login", "/register", "/error", "/favicon.ico"};
        for (String path : publicPaths) {
            if (uri.equals(path) ||
                    uri.startsWith("/css/") ||
                    uri.startsWith("/js/") ||
                    uri.startsWith("/img/") ||
                    uri.startsWith("/fonts/") ||
                    uri.startsWith("/api/")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理未授权访问
     */
    private void handleUnauthorized(HttpServletRequest request, HttpServletResponse response, String method) throws Exception {
        // AJAX请求特殊处理
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请重新登录");
            return;
        }

        // 对于POST请求，使用重定向避免405错误（新增关键逻辑）
        if ("POST".equalsIgnoreCase(method)) {
            response.sendRedirect(request.getContextPath() + "/login?expired=true");
        }
        // 普通GET请求保持您原有的转发逻辑
        else {
            request.setAttribute("msg", "请先登录");
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

    /**
     * 角色权限检查（封装您原有逻辑）
     */
    private boolean checkRolePermission(String uri, Object roleObj) throws Exception {
        if (!(roleObj instanceof Integer)) return false;
        int role = (Integer) roleObj;

        // 放行特定路径（保持您原有逻辑）
        if (uri.startsWith("/admin/list") || uri.startsWith("/admin/search")) {
            return true;
        }

        // 角色检查（保持您原有逻辑）
        if (uri.startsWith("/admin/") && role != 1) {
            throw new Exception("无权访问管理员功能");
        }
        if (uri.startsWith("/superadmin/") && role != 2) {
            throw new Exception("需要超级管理员权限");
        }

        return true;
    }

    // 保持您原有的postHandle和afterCompletion方法不变
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}